import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

n_values = [2, 4, 6, 8]
plt.figure(figsize=(10, 8))

for n in n_values:
    try:
        data = pd.read_csv(f'data_n{n}.csv', header=None)
        plt.plot(data.to_numpy()[:, 0], data.to_numpy()[:, 1], label=f'n={n}', marker='o')  # 转换为 NumPy 数组
    except FileNotFoundError:
        print(f"File data_n{n}.csv not found.")
    except Exception as e:
        print(f"An error occurred while processing data_n{n}.csv: {e}")

# 绘制精确函数
x_exact = np.linspace(-5, 5, 400)
y_exact = 1 / (1 + x_exact**2)
plt.plot(x_exact, y_exact, 'k--', label='Exact function')

# 添加图例和标签
plt.legend()
plt.title('Runge Phenomenon')
plt.xlabel('X')
plt.ylabel('f(X)')
plt.grid(True)

# 保存图像
plt.savefig('runge_phenomenon.png')
plt.show()
